import 'dart:convert';
import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:zhibao_flutter/api/wallet/wallet_entity.dart';
import 'package:zhibao_flutter/api/wallet/wallet_view_model.dart';
import 'package:zhibao_flutter/dialog/offset_team_menu.dart';
import 'package:zhibao_flutter/pages/home/bubble_model.dart';
import 'package:zhibao_flutter/widget/animate/bubble.dart';
import 'package:zhibao_flutter/widget/bt/maginc_bt.dart';
import 'package:zhibao_flutter/widget/data/loading_view.dart';
import 'package:zhibao_flutter/widget/scrol/my_behavior.dart';
import 'package:zhibao_flutter/zone.dart';

//团队架构
class BubbleNewPage extends StatefulWidget {
  final int? showGrade;

  BubbleNewPage([this.showGrade]);

  @override
  _BubbleNewPageState createState() => _BubbleNewPageState();
}

class _BubbleNewPageState extends State<BubbleNewPage>
    with AutomaticKeepAliveClientMixin {
  // MockBubbleModel? model;

  // List<TeamEntity> teamList = [];

  List<TeamStructureEntity> teamStructureList = [];

  // int total = 0;
  int levelItem = 0;

  @override
  void initState() {
    super.initState();
    levelItem = widget.showGrade ?? Q1Data.grade;
    getData();
  }

  void getData() async {
    // String loadString = await rootBundle.loadString("assets/data/home.json");
    // // model = MockBubbleModel.fromJson(json.decode(loadString));
    // setState(() {});
    // await getTeamData();
    await getUserMyTeamStructure(null);
  }

  // Future getTeamData() async {
  //   // active
  //   // integer($int32)
  //   //   (query)
  //   // 激活 0:未激活 1激活 null: 获取全部
  //   // 激活就是有1级的用户，默认是0级，要充值等操作然后手动升级。
  //   final int? active = null;
  //
  //   final value =
  //       await walletViewModel.userMyTeam(null, active: active, page: 1);
  //   if (value.data == null) {
  //     return;
  //   }
  //   TeamEntityTotalData totalData = value.data!;
  //   // teamList = totalData.dataList;
  //   total = totalData.total;
  //   if (mounted) setState(() {});
  // }

  Future getUserMyTeamStructure(BuildContext? context) async {
    final value = await walletViewModel.userMyTeamStructure(context, levelItem);
    if (value.data == null) {
      /// If context equal null that means the user has no permission to access the page.
      if (context == null) {
        Get.back();
      }
      return;
    }
    teamStructureList = value.data!;
    // 【2024 Feb 29】
    // 如图更改钻石排列位置【自己永远在C位】。
    teamStructureList.sort((a, b) {
      if (a.userId == Q1Data.id) {
        return 0;
      } else {
        return a.num!.compareTo(b.num!) + 1;
      }
    });
    LogUtil.d(
        "teamStructureList::[getUserMyTeamStructure]::${json.encode(teamStructureList)}");
    LogUtil.d(
        "teamStructureList 的顺序是${teamStructureList.map((e) => e.num).toList()}");
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return MyScaffold(
      overlayStyle: SystemUiOverlayStyle.light,
      backgroundColor: Color(0xff1f1923),
      body:
          // model == null
          //     ? new LoadingView()
          //     :
          Column(
        children: [
          Container(
            color: Color(0xff1f1923),
            height: FrameSize.statusBarHeight(),
          ),
          Row(
            children: [
              Space(),
              InkwellWithOutColor(
                child: SizedBox(
                  height: 60.px,
                  width: 60.px,
                  child: Icon(
                    Icons.arrow_back_ios,
                    color: Colors.white,
                  ),
                ),
                onTap: () {
                  Get.back();
                },
              )
            ]
              ..addAll([
                {"ic": "ic_diamond.png", "value": "$levelItem${"level".tr}"}, //
                {
                  "ic": "ic_yuan_li.png",
                  "value":
                      "${teamStructureList.length > 0 ? (teamStructureList.first.teamStructureCount ?? 0) : 0}${"people".tr}",
                  // "value": "${total.value}人",
                },
              ].map((e) {
                final bool diamond = e['ic'] == "ic_diamond.png";
                return Builder(builder: (BuildContext context) {
                  return MagicBt(
                    margin: EdgeInsets.only(right: diamond ? 20.px : 0),
                    width: (diamond ? 93.px : 82.px) + 30.px,
                    padding: EdgeInsets.zero,
                    minHeight: 26.px,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset('assets/images/ic/${e['ic']}',
                            width: 25.06.px),
                        Space(width: 5.px),
                        Text(
                          '${e['value']}',
                          style:
                              TextStyle(color: Colors.white, fontSize: 16.px),
                        ),
                        Space(width: 4.px),
                        if (diamond) ...[
                          Image.asset('assets/images/ic/ic_arrow_down.png',
                              width: 10.px),
                        ]
                      ],
                    ),
                    onTap: () async {
                      if (!diamond) {
                        return;
                      }
                      RenderBox box = context.findRenderObject() as RenderBox;
                      Offset offset = box.localToGlobal(Offset.zero);
                      print("点击的位置:offset:$offset");
                      final value = await offsetTeamMenu(context, offset);
                      if (value != null && value is int) {
                        levelItem = value;
                        await getUserMyTeamStructure(context);
                      }
                      // if (!_isLogin) {
                      //   unLoginDialog(context);
                      // } else if (e['ic'] == 'ic_yuan_li.png') {
                      //   Get.to(new ForceValuePage());
                      // } else {
                      //   Get.to(new ForceValuePage(ValueType.diamond));
                      // }
                    },
                  );
                });
              }).toList())
              ..addAll([
                // new Spacer(),
                // new InkWell(
                //   child: new Container(
                //     padding: EdgeInsets.symmetric(
                //         vertical: 5, horizontal: 10),
                //     child: new Image.asset(
                //       'assets/images/ic/ic_msg.png',
                //       width: 25,
                //     ),
                //   ),
                //   onTap: () {
                //     // if (_isLogin) {
                //     //   Get.to(new MsgPage());
                //     // } else {
                //     //   unLoginDialog(context);
                //     // }
                //   },
                // ),
              ]),
          ),
          Expanded(
            child: ListView(
              padding: EdgeInsets.all(0),
              children: [
                Space(),
                Container(
                  width: FrameSize.winWidth(),
                  height: (FrameSize.winHeight() * 828 / 750) / 1.35,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/images/ic/bg_star.png'),
                      alignment: Alignment.topCenter,
                    ),
                  ),
                  child: Column(
                    children: [
                      // new Container(
                      //   padding: EdgeInsets.symmetric(horizontal: 15),
                      //   margin: EdgeInsets.symmetric(horizontal: 10),
                      //   decoration: BoxDecoration(
                      //     color: Color(0xff272142),
                      //     borderRadius:
                      //         BorderRadius.all(Radius.circular(30)),
                      //   ),
                      //   child: new Row(
                      //     children: [
                      //       new Image.asset(
                      //         'assets/images/ic/home_notice.png',
                      //         width: 15,
                      //       ),
                      //       new Space(width: 5),
                      //       new Expanded(
                      //         child: new SizedBox(
                      //           height: 35,
                      //           child: new Marquee(
                      //             text:
                      //                 '【购物频道】秋凉季节一起来抢优惠，满满满满满300-30！倒计时。',
                      //             style: TextStyle(color: Colors.white),
                      //             blankSpace: 20,
                      //           ),
                      //         ),
                      //       ),
                      //       new Space(width: 5),
                      //       new InkWell(
                      //         child: new Row(
                      //           children: [
                      //             new Text(
                      //               '更多',
                      //               style: TextStyle(
                      //                 color:
                      //                     Colors.white.withOpacity(0.7),
                      //               ),
                      //             ),
                      //             new Icon(
                      //               CupertinoIcons.right_chevron,
                      //               color: Colors.white.withOpacity(0.7),
                      //               size: 15,
                      //             ),
                      //           ],
                      //         ),
                      //         onTap: () {
                      //           // if (_isLogin) {
                      //           //   Get.to(new NoticePage());
                      //           // } else {
                      //           //   unLoginDialog(context);
                      //           // }
                      //         },
                      //       )
                      //     ],
                      //   ),
                      // ),
                      Expanded(
                        child: Stack(
                          children: List.generate(7, (index) {
                            return Bobbles(
                                index: index,
                                teamStructureList: teamStructureList);
                          }),
                        ),
                      ),
                      ScrollConfiguration(
                        behavior: MyBehavior(),
                        child: SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          child: Row(
                            children: List.generate(7, (index) {
                              return ActionCard(index < teamStructureList.length
                                  ? teamStructureList[index]
                                  : null);
                            }),
                          ),
                          // child: new Row(
                          //   children: teamStructureList
                          //           .map((e) => new ActionCard(e))
                          //           .toList() ??
                          //       [],
                          // ),
                        ),
                      ),
                    ],
                  ),
                ),
                // new Padding(
                //   padding:
                //       EdgeInsets.symmetric(vertical: 25, horizontal: 10),
                //   child: new Row(
                //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
                //     children: [
                //       new Text(
                //         '星球精选',
                //         style:
                //             TextStyle(color: Colors.white, fontSize: 20),
                //       ),
                //       new Text(
                //         '昨日已瓜分39.5W贡献值',
                //         style: TextStyle(
                //             color: Colors.white.withOpacity(0.5)),
                //       )
                //     ],
                //   ),
                // ),
                // new Padding(
                //   padding: EdgeInsets.symmetric(horizontal: 15),
                //   child: new Wrap(
                //     spacing: 10,
                //     runSpacing: 10,
                //     children: List.generate(
                //         model?.jumpPages?.verticalJumpPages?.length ?? 0,
                //         (index) {
                //       VerticalJumpPages inModel =
                //           model!.jumpPages!.verticalJumpPages[index];
                //       return new GameCard(inModel);
                //     }),
                //   ),
                // ),
                Container(
                  padding: EdgeInsets.only(top: 50, bottom: 20),
                  width: FrameSize.winWidth(),
                  alignment: Alignment.center,
                  child: Text(
                    '- ${"bottomLine".tr} -',
                    style: TextStyle(color: MyTheme.mainTextColor()),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class ActionModel {
  final String topTip;
  final String bottomTip;
  final String title;
  final String icon;

  ActionModel(this.topTip, this.icon, this.title, this.bottomTip);
}

class ActionCard extends StatelessWidget {
  final TeamStructureEntity? model;

  ActionCard(this.model);

  @override
  Widget build(BuildContext context) {
    final bool notSelf = model?.userId != Q1Data.id;
    return GestureDetector(
      child: Container(
        width: (FrameSize.winWidth() / 3) + 10,
        decoration: BoxDecoration(
          color: Color(0xff272142),
          borderRadius: BorderRadius.all(Radius.circular(10)),
        ),
        padding: EdgeInsets.symmetric(horizontal: 10, vertical: 15),
        height: 132.px + 20.px,
        margin: EdgeInsets.only(left: 10, right: 5),
        child: Column(
          children: model == null
              ? [
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 10),
                    child: Image.asset(
                      "assets/images/ic/bubble_main_logo.png",
                      width: 45,
                      color: Colors.grey,
                    ),
                  ),
                  Text(
                    'noMembers'.tr,
                    style: TextStyle(color: Colors.white),
                  )
                ]
              : [
                  /// 自己不显示位置
                  if (notSelf)
                    Text(
                      "${"position".tr}: ${model!.num ?? ''}",
                      style: TextStyle(color: Colors.white),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 10),
                    child: Image.asset(
                      "assets/images/ic/bubble_main_logo.png",
                      width: 45,
                    ),
                  ),
                  Text(
                    "${"user".tr}: ${!notSelf ? "self".tr : end4Phone(model!.phone)}",
                    style: TextStyle(color: Colors.white),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  Text(
                    "${"referrer".tr}: ${end4Phone(model!.referrerPhone ?? '0000')}",
                    style: TextStyle(color: Colors.white),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  // new Text(
                  //   'VIP${model.num}',
                  //   style: TextStyle(color: Colors.white),
                  // ),
                  Space(height: 3),
                  // new Text(
                  //   'id:${model.userId}',
                  //   style:
                  //   TextStyle(color: Colors.white.withOpacity(0.5), fontSize: 11),
                  // ),
                ],
        ),
      ),
      onTap: () {
        // action(model);
      },
    );
  }

  void action(HorizontalJumpPages model) {
//     if (model.title.contains('游戏')) {
//       Get.to(new GamePage());
//     } else if (model.title.contains('阅读')) {
//       Get.to(new FictionPage());
//     } else if (model.title.contains('视频')) {
//       Get.to(new TikTokPage());
// //      Get.to(new VideoPage());
//     } else if (model.title.contains('资讯')) {
//       showToast('敬请期待');
//     } else {
//       Get.to(new ShoppingPage());
//     }
  }
}
